# -*- coding: utf-8 -*-
# 作   者 ：许亦安
# 邮   箱 ：xuyian_dev@foxmail.com
# 创建时间 ：2020/10/22  17:54
# 项目名称 ：HFYG
# 文件名称 ：GetByRequests.py
# 开发工具 ：PyCharm

import requests
import parsel
import time
import xlrd
import os
from bs4 import BeautifulSoup



# 获取验证码
def get_data(r):
    selector = parsel.Selector(r.text)
    # 验证码
    verification_code = selector.css('#lblTest::text').extract()[0]
    # cookie
    cookies = r.cookies
    # 百度的
    s = BeautifulSoup(r.text, "html.parser")
    # __VIEWSTATE
    view_state = s.find('input', id='__VIEWSTATE')["value"]
    # __EVENTVALIDATION
    event_validation = s.find('input', id="__EVENTVALIDATION")["value"]
    return [verification_code, cookies, view_state, event_validation]


# 登录post请求
def do_post():
    pass


# 登录并返回分数详情页
def login(name, pd):
    # 请求主页，从主页响应获取登录时post请求所需参数（验证码、页面隐藏信息等）、cookie（验证码可用性）
    index_response = requests.get(index_url)
    # 获取本次登录请求的验证信息
    list_data = get_data(index_response)
    # 验证码
    code = list_data[0]
    print("准考证号：", name, "密码：", pd, "验证码：", code)
    # cookie
    cookies = list_data[1].get_dict()
    print("cookies：ASP.NET_SessionId=" + cookies['ASP.NET_SessionId'])
    # view_state
    vs = list_data[2]
    print("__VIEWSTATE：" + vs)
    # event_validation
    ev = list_data[3]
    print("__EVENTVALIDATION：" + ev)
    headers1 = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image"
                  + "/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Content-Length": "598",
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "ASP.NET_SessionId=" + cookies['ASP.NET_SessionId'],
        "Host": "zk.ahzsks.cn",
        "Origin": "http: // zk.ahzsks.cn",
        "Referer": "http: // zk.ahzsks.cn / Login.aspx",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                      + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"
    }
    data = {
        "__LASTFOCUS": "",
        "__EVENTTARGET": "",
        "__EVENTARGUMENT": "",
        "__VIEWSTATE": vs,
        "__EVENTVALIDATION": ev,
        "txtAdmissionTicket": str(name),
        "txtPassWord": str(pd),
        "txtTest": code,
        "btnLogin.x": "66",
        "btnLogin.y": "22"
    }
    requests_post = requests.post(login_url, data=data, headers=headers1)
    return requests_post


# 主页路径
index_url = 'http://zk.ahzsks.cn'
# 登录请求路径
login_url = 'http://zk.ahzsks.cn/Login.aspx'
# 考生账密文件路径
stu_xlsx_path = "./data/考生账密.xlsx"
stu_xls_path = "./data/考生账密.xls"
# 查询结果存放路径
result_path = "./data/考生分数查询结果.xlsx"

if __name__ == '__main__':
    # 判断账密文件是否存在
    if os.path.exists(stu_xlsx_path):
        # 存在，获取sheet
        sheet = xlrd.open_workbook(stu_xlsx_path).sheet_by_index(0)
        total_row = sheet.nrows
        start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        # for i in range(1, total_row + 1):
        for i in range(1, 2):
            user_name = sheet.row_values(i)[0]
            password = sheet.row_values(i)[1]
            response = login(user_name, password)
            print("第" + str(i) + "次访问---起始时间：" + start_time
                  + "---当前时间：" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
            # print(response.text)
            i += 1
    else:
        # 不存在
        print("考生账密文件不存在！")
